<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Region, Riderlist, RiderStreet, Order, Orderlog, Graborder, Message, CateSons, AreaPrice, Drivers, DriversAuth, DriverStreet, Carlist, Carorder};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;
use EasyWeChat\Factory;

class Driver extends Base
{
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '登录手机号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Drivers())->where('mobile', $data['mobile'])->find();
        $token = 'Driver' . md5(md5($user['id'] . time()));
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '密码错误');
        }
        Redis::setex($token, 86400 * 7, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function register()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '注册手机号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Drivers())->where('mobile', $data['mobile'])->find();
        if (!empty($user)) {
            $this->result([], 1, '手机号已被使用');
        }
        $password = md5(md5($data['password']));
        $id = (new Drivers())->insertGetId(['mobile' => $data['mobile'], 'password' => $password, 'status' => 3, 'user_id' => $this->request->user_id ?? 0]);
        $token = 'Driver' . md5(md5($id . time()));
        if ($id) {
            Redis::setex($token, 86400 * 7, $id);
            $this->result(['token' => $token], 0, '注册成功');
        }
        $this->result([], 1, '注册失败，请重试');
    }

    public function infos()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'cards' => 'require',
                'icards' => 'require',
                'pcards' => 'require',
                'carcolor' => 'require|in:1,2,3',
                'carcards' => 'require',
                'type' => 'require|in:1,2,3',
                'jszimg' => 'require',
                'xszimg1' => 'require',
                'xszimg2' => 'require',
            ], [
                'name.require' => '用户名不能为空',
                'cards.require' => '身份证号不能为空',
                'icards.require' => '身份图片不能为空',
                'pcards.require' => '身份图片不能为空',
                'carcolor.require' => '车牌颜色不能为空',
                'carcolor.in' => '车牌类型不正确',
                'carcards.require' => '车牌号不能为空',
                'type.require' => '驾驶证类型不能为空',
                'type.in' => '驾驶证类型不正确',
                'jszimg.require' => '驾驶证图片不能为空',
                'xszimg1.require' => '行驶证图片不能为空',
                'xszimg2.require' => '行驶证图片不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $driversauth = (new DriversAuth())->where('driversid', $this->request->driver_id)->find();
            if (!empty($driversauth)) {
                $res = (new DriversAuth())->allowfield(true)->save($data, ['driversid' => $this->request->driver_id]);
            } else {
                $data['driversid'] = $this->request->driver_id;
                $res = (new DriversAuth())->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '保存成功');
            }
            $this->result([], 1, '保存失败，请重试');
        } else {
            $driversauth = (new DriversAuth())->where('driversid', $this->request->driver_id)->find();
            $this->result($driversauth, 0, '获取成功');
        }
    }


    public function streets()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'street' => 'require'
            ], [
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //判断是否存在该街道记录
            $RiderStreet = (new DriverStreet())->where(['driverid' => $this->request->driver_id, 'street' => $data['street']])->find();
            if (!empty($RiderStreet) && $RiderStreet['status'] == 2) {
                $this->result([], 1, '您已是该街道的骑手，无需重复申请');
            }
            if (!empty($RiderStreet) && $RiderStreet['status'] == 1) {
                $this->result([], 1, '该街道的申请待合伙人审核，无需重复申请');
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['area'] = $area['area_code'];
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $data['city'] = $city['area_code'];
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $data['province'] = $province['area_code'];
            Db::startTrans();
            try {
                if (!empty($RiderStreet)) {
                    (new DriverStreet())->where('id', $RiderStreet['id'])->update([
                        'driverid' => $this->request->reder_iddriver_id,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                } else {
                    (new DriverStreet())->insert([
                        'driverid' => $this->request->driver_id,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new DriverStreet())->field('provinceid,cityid,areaid,street,status')->where(['driverid' => $this->request->driver_id])->select();
            foreach ($list as $lists) {
                $lists['province_text'] = (new Region())->where(['area_code' => $lists['provinceid']])->value('name');
                $lists['city_text'] = (new Region())->where(['area_code' => $lists['cityid']])->value('name');
                $lists['area_text'] = (new Region())->where(['area_code' => $lists['areaid']])->value('name');
                $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function getproduct()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'ids' => 'require'
            ], [
                'ids.require' => '服务项目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $ids = json_decode($data['ids'], true) ?? [];
            $ids = array_unique($ids);
            if (count($ids) <= 0) {
                $this->result([], 1, '请选择服务项目');
            }
            $ids = json_encode($ids, true);
            $res = (new Drivers())->where(['id' => $this->request->driver_id])->update(['product' => $ids]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $streets = (new DriverStreet())->field('provinceid,cityid,areaid,street,status')->where(['driverid' => $this->request->driver_id, 'status' => 2])->select();
            $lists = [];
            foreach ($streets as $streeta) {
                $street = $streeta['street'];
                $area = (new Region())->where(['id' => $street, 'level' => 4])->value('area_code') ?? 0;
                $where = [
                    'street' => $street
                ];
                $where1 = [
                    'street' => $street,
                    'area' => $area,
                ];
                $ids = (new Carlist())
                    ->whereOr(function ($query) use ($where) {
                        $query->where($where);
                    })->whereOr(function ($query) use ($where1) {
                        $query->where($where1);
                    })->column('id');
                if (count($ids) > 0) {
                    $lists = array_merge($lists, $ids);
                }
            }
            $lists = array_unique($lists);
            $result =  (new Carlist())->where(['id' => $lists])->field('id,title')->select();
            $this->result($result, 0, '获取成功');
        }
    }

    public function info()
    {
        $time = date('Y-m-d') . ' 00:00:00';
        $endtime = date('Y-m-d') . ' 23:59:59';
        $product = json_decode($this->request->driver['product'], true);
        $result = [
            'mobile' => $this->request->driver['mobile'],
            'name' => (new DriversAuth())->where('driversid', $this->request->driver_id)->value('name') ?? '未认证',
            'status' => $this->request->driver['status'],
            'order' => (new Carorder())->where('orders_id', $this->request->driver_id)->count(),
            'todayorder' => (new Carorder())->where('orders_id', $this->request->driver_id)->whereBetweenTime('puttime', $time, $endtime)
                ->count(),
            'product' => $product,

        ];
        $this->result($result, 0, '获取成功');
    }


    public function orderlist()
    {
        $list = (new Carorder())->order('appoint desc');
        $status = $this->request->get('status/d', 1);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        if ($status == 2) {
            $street = (new DriverStreet())->where(['driverid' =>  $this->request->driver_id, 'status' => 2])->column('street');
            if (empty($street)) {
                $this->result([], 0, '获取成功');
            }
            $product = json_decode($this->request->driver['product'], true);
            $list = $list->where(['street' => $street, 'listid' => $product]);
        } else {
            $list = $list->where('orders_id', $this->request->driver_id);
        }
        $list = $list->field('id,type,address,status,appoint,total,listname,mobile')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lis) {
            $lis['address'] = json_decode($lis['address'], true);
            $lis['status_text'] = $lis->status_text;
        }
        $this->result($list, 0, '获取成功');
    }


    public function cdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Carorder())->field('id,type,ordersn,appoint,address,fee,status,ispay,ishave,bighand,sfloor,efloor,mobile,listname,km,lc,total,remark')->where('id', $id)->find();
        if ($lists) {
            $lists['address'] = json_decode($lists['address'], true);
            $lists['fee'] = json_decode($lists['fee'], true);
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($lists, 0, '获取成功');
    }

    public function putorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:3,4,5',
            ], [
                'id.require' => '订单ID不能为空',
                'status.require' => '订单状态不能为空',
                'status.in' => '订单类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Carorder())->where('id', $data['id'])->where(['status' => [2, 3]])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在或已完成');
            }
            switch ($data['status']) {
                case '3':
                    if ($order['status'] != 2) {
                        $this->result([], 1, '订单状态不可接单');
                    }
                    $product = json_decode($this->request->driver['product'], true);
                    if (!in_array($order['listid'], $product)) {
                        $this->result([], 1, '服务车辆类型不可接单');
                    }
                    $street = (new DriverStreet())->where(['driverid' =>  $this->request->driver_id, 'status' => 2, 'street' => $order['street']])->find();
                    if (empty($street)) {
                        $this->result([], 1, '无该街道接单权限');
                    }
                    $res = (new Carorder())->where('id', $data['id'])->update(['status' => 3, 'puttime' => date('Y-m-d H:i:s'), 'orders_id' =>  $this->request->driver_id]);
                    break;
                case '4':
                    if ($order['status'] != 3) {
                        $this->result([], 1, '订单状态不可确认');
                    }
                    if ($order['orders_id'] != $this->request->driver_id) {
                        $this->result([], 1, '无该订单操作权限');
                    }
                    $res = (new Carorder())->where('id', $data['id'])->update(['status' => 4, 'finshtime' => date('Y-m-d H:i:s')]);
                    break;
                case '5':
                    if ($order['status'] != 3) {
                        $this->result([], 1, '订单状态不可取消');
                    }
                    if ($order['orders_id'] != $this->request->driver_id) {
                        $this->result([], 1, '无该订单操作权限');
                    }
                    if ($order['ispay'] != 1) {
                        $this->result([], 1, '在线支付订单暂时不支持取消');
                    }
                    $res = (new Carorder())->where('id', $data['id'])->update(['status' => 5, 'caceltime' => date('Y-m-d H:i:s')]);
                    break;
                default:
                    $this->result([], 1, '状态错误');
                    break;
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }
}